/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kreig133.analytic.statistic;

import com.kreig133.analytic.interfaces.ViewDataHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 *
 * @author C.C.-fag
 */
public class SimpleMovingAverageHandler implements ViewDataHandler {
    
    private int koeff = 0;
    private ViewDataHandler previousHandler;

    /**
     *
     * @param nextHandler - предшествующий обработчик
     * @param periodsCount - степень сглаживания (количество периодов).
     */
    public SimpleMovingAverageHandler(ViewDataHandler nextHandler) {
        this.previousHandler = nextHandler;
    }

    public void setKoeff(Integer periodsCount) {
        if(this.koeff!=0) return;
        this.koeff = periodsCount;
    }

    
    public strictfp Map<Double, Double> getProcessedData() throws Exception {
        Map<Double, Double> temp = previousHandler.getProcessedData();
        Map<Double, Double> result = new TreeMap<Double, Double>() {};

        List<Double> list = new ArrayList<Double>();
        list.addAll(temp.keySet());
        Collections.sort(list);
        double sum = 0;

        for(int i=0 ; i<(list.size()-koeff); i++){
            sum=0;
            for(int j=0; j < koeff; j++){
                 sum += temp.get(list.get(i+j));
            }
            result.put(list.get(i), sum/koeff);
        }
        return result;
    }
    
}
